/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.repairitem.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.core.enums.BizDataTypeEnum;
import vip.xiaonuo.biz.modular.org.entity.BizOrg;
import vip.xiaonuo.biz.modular.repair.entity.RepairApply;
import vip.xiaonuo.biz.modular.repair.service.RepairApplyService;
import vip.xiaonuo.biz.modular.repairitem.entity.RepairItem;
import vip.xiaonuo.biz.modular.repairitem.mapper.RepairItemMapper;
import vip.xiaonuo.biz.modular.repairitem.param.RepairItemAddParam;
import vip.xiaonuo.biz.modular.repairitem.param.RepairItemEditParam;
import vip.xiaonuo.biz.modular.repairitem.param.RepairItemIdParam;
import vip.xiaonuo.biz.modular.repairitem.param.RepairItemPageParam;
import vip.xiaonuo.biz.modular.repairitem.service.RepairItemService;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.listener.CommonDataChangeEventCenter;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.sys.api.SysRoleApi;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 维修项目Service接口实现类
 *
 * @author chbzheng
 * @date  2023/06/12 19:45
 **/
@Service
public class RepairItemServiceImpl extends ServiceImpl<RepairItemMapper, RepairItem> implements RepairItemService {

    @Override
    public Page<RepairItem> page(RepairItemPageParam repairItemPageParam) {
        QueryWrapper<RepairItem> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(repairItemPageParam.getParentId())) {
            queryWrapper.lambda().eq(RepairItem::getParentId, repairItemPageParam.getParentId());
        }
        if(ObjectUtil.isNotEmpty(repairItemPageParam.getType())) {
            queryWrapper.lambda().eq(RepairItem::getType, repairItemPageParam.getType());
        }
        if(ObjectUtil.isNotEmpty(repairItemPageParam.getCode())) {
            queryWrapper.lambda().like(RepairItem::getCode, repairItemPageParam.getCode());
        }
        if(ObjectUtil.isNotEmpty(repairItemPageParam.getName())) {
            queryWrapper.lambda().like(RepairItem::getName, repairItemPageParam.getName());
        }
        if(ObjectUtil.isNotEmpty(repairItemPageParam.getEnable())) {
            queryWrapper.lambda().eq(RepairItem::getEnable, repairItemPageParam.getEnable());
        }
        if(ObjectUtil.isAllNotEmpty(repairItemPageParam.getSortField(), repairItemPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(repairItemPageParam.getSortOrder());
            queryWrapper.orderBy(true, repairItemPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(repairItemPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(RepairItem::getSortCode);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    public static final String REPAIRITEM_CACHE_ALL_KEY = "biz-repairitem:all";

    @Resource
    private CommonCacheOperator commonCacheOperator;
    @Resource
    private RepairApplyService repairApplyService;


    @Resource
    private SysRoleApi sysRoleApi;

    public List<RepairItem> findTopList() {
        List<RepairItem> list = this.list(new LambdaQueryWrapper<RepairItem>().eq(RepairItem::getParentId, "0")
                .orderByAsc(RepairItem::getSortCode));
        return list;
    }

    @Override
    public List<Tree<String>> tree() {
        // 获取所有机构
        List<RepairItem> allOrgList = this.list();
        // 定义机构集合
        Set<RepairItem> bizOrgSet = CollectionUtil.newHashSet();
        // 校验数据范围
        List<RepairItem> tops = findTopList();
        if (tops == null || tops.isEmpty()) {
            return CollectionUtil.newArrayList();
        }
        //List<String> loginUserDataScope = CollStreamUtil.toList(tops, RepairItem::getId);
        /*
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        loginUserDataScope.forEach(orgId -> bizOrgSet.addAll(this.getParentListById(allOrgList, orgId, true)));
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            loginUserDataScope.forEach(orgId -> bizOrgSet.addAll(this.getParentListById(allOrgList, orgId, true)));
        } else {
            return CollectionUtil.newArrayList();
        }*/
        List<TreeNode<String>> treeNodeList = allOrgList.stream().map(bizOrg ->
                new TreeNode<>(bizOrg.getId(), bizOrg.getParentId(),
                        bizOrg.getName(), bizOrg.getSortCode()).setExtra(JSONUtil.parseObj(bizOrg)))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(RepairItemAddParam bizOrgAddParam) {
        //RepairItemCategoryEnum.validate(bizOrgAddParam.getCategory());
        // 校验数据范围
        /*
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(bizOrgAddParam.getParentId())) {
                throw new CommonException("您没有权限在该机构下增加机构，机构id：{}", bizOrgAddParam.getParentId());
            }
        } else {
            throw new CommonException("您没有权限增加机构");
        }*/
        RepairItem bizOrg = BeanUtil.toBean(bizOrgAddParam, RepairItem.class);

        // 重复名称
        boolean repeatName = this.count(new LambdaQueryWrapper<RepairItem>().eq(RepairItem::getParentId, bizOrg.getParentId())
                .eq(RepairItem::getName, bizOrg.getName())) > 0;
        if(repeatName) {
            throw new CommonException("存在重复的同级类型，名称为：{}", bizOrg.getName());
        }
        bizOrg.setCode(RandomUtil.randomString(10));
        this.save(bizOrg);

        // 发布增加事件
        CommonDataChangeEventCenter.doAddWithData(BizDataTypeEnum.REPAIRITEM.getValue(), JSONUtil.createArray().put(bizOrg));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(RepairItemEditParam bizOrgEditParam) {
        //RepairItemCategoryEnum.validate(bizOrgEditParam.getCategory());
        RepairItem bizOrg = this.queryEntity(bizOrgEditParam.getId());
        /*
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(bizOrg.getId())) {
                throw new CommonException("您没有权限编辑该机构，机构id：{}", bizOrg.getId());
            }
            if(!loginUserDataScope.contains(bizOrg.getParentId())) {
                throw new CommonException("您没有权限编辑该机构下的机构，机构id：{}", bizOrg.getParentId());
            }
        } else {
            throw new CommonException("您没有权限编辑该机构，机构id：{}", bizOrg.getId());
        }*/
        BeanUtil.copyProperties(bizOrgEditParam, bizOrg);
        boolean repeatName = this.count(new LambdaQueryWrapper<RepairItem>().eq(RepairItem::getParentId, bizOrg.getParentId())
                .eq(RepairItem::getName, bizOrg.getName()).ne(RepairItem::getId, bizOrg.getId())) > 0;
        if(repeatName) {
            throw new CommonException("存在重复的同级机构，名称为：{}", bizOrg.getName());
        }
        List<RepairItem> originDataList = this.list();
        boolean errorLevel = this.getChildListById(originDataList, bizOrg.getId(), true).stream()
                .map(RepairItem::getId).collect(Collectors.toList()).contains(bizOrg.getParentId());
        if(errorLevel) {
            throw new CommonException("不可选择上级机构：{}", this.getById(originDataList, bizOrg.getParentId()).getName());
        }
        this.updateById(bizOrg);

        // 发布更新事件
        CommonDataChangeEventCenter.doUpdateWithData(BizDataTypeEnum.REPAIRITEM.getValue(), JSONUtil.createArray().put(bizOrg));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<RepairItemIdParam> bizOrgIdParamList) {
        List<String> orgIdList = CollStreamUtil.toList(bizOrgIdParamList, RepairItemIdParam::getId);
        if(ObjectUtil.isNotEmpty(orgIdList)) {
            // 校验数据范围
            List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
            if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
                if(!loginUserDataScope.containsAll(orgIdList)) {
                    throw new CommonException("您没有权限删除这些机构，机构id：{}", orgIdList);
                }
            } else {
                throw new CommonException("您没有权限删除这些机构，机构id：{}", orgIdList);
            }
            List<RepairItem> allOrgList = this.list();
            // 获取所有子机构
            List<String> toDeleteOrgIdList = CollectionUtil.newArrayList();
            orgIdList.forEach(orgId -> toDeleteOrgIdList.addAll(this.getChildListById(allOrgList, orgId, true).stream()
                    .map(RepairItem::getId).collect(Collectors.toList())));
            // 机构下有人不能删除（直属机构）

            boolean hasOrgUser = repairApplyService.count(new LambdaQueryWrapper<RepairApply>().in(RepairApply::getRepairItemId, toDeleteOrgIdList)) > 0;
            if(hasOrgUser) {
                throw new CommonException("请先删除机构下的人员");
            }
            // 机构下有人不能删除（兼任机构）


            // 执行删除
            this.removeByIds(toDeleteOrgIdList);

            // 发布删除事件
            CommonDataChangeEventCenter.doDeleteWithDataId(BizDataTypeEnum.REPAIRITEM.getValue(), toDeleteOrgIdList);
        }
    }

    @Override
    public RepairItem detail(RepairItemIdParam bizOrgIdParam) {
        return this.queryEntity(bizOrgIdParam.getId());
    }

    @Override
    public RepairItem queryEntity(String id) {
        RepairItem bizOrg = this.getById(id);
        if(ObjectUtil.isEmpty(bizOrg)) {
            throw new CommonException("机构不存在，id值为：{}", id);
        }
        return bizOrg;
    }

    @Override
    public List<RepairItem> getCachedAllRepairItemList() {
        // 从缓存中取
        Object cacheValue = commonCacheOperator.get(REPAIRITEM_CACHE_ALL_KEY);
        if(ObjectUtil.isNotEmpty(cacheValue)) {
            return JSONUtil.toList(JSONUtil.parseArray(cacheValue), RepairItem.class);
        }
        List<RepairItem> orgList = this.list(new LambdaQueryWrapper<RepairItem>().orderByAsc(RepairItem::getSortCode));
        if(ObjectUtil.isNotEmpty(orgList)) {
            // 更新到缓存
            commonCacheOperator.put(REPAIRITEM_CACHE_ALL_KEY, JSONUtil.toJsonStr(orgList));
        }
        return orgList;
    }

    @Override
    public String getRepairItemIdByFullNameWithCreate(String orgFullName) {
        List<RepairItem> cachedAllOrgList = this.getCachedAllRepairItemList();
        List<Tree<String>> treeList = TreeUtil.build(cachedAllOrgList.stream().map(bizOrg ->
                new TreeNode<>(bizOrg.getId(), bizOrg.getParentId(), bizOrg.getName(), bizOrg.getSortCode()))
                .collect(Collectors.toList()), "0");
        return findRepairItemIdByName("0", StrUtil.split(orgFullName, StrUtil.DASHED).iterator(), cachedAllOrgList, treeList);
    }

    public String findRepairItemIdByName(String parentId, Iterator<String> iterator, List<RepairItem> cachedAllOrgList, List<Tree<String>> treeList) {
        String orgName = iterator.next();
        if(ObjectUtil.isNotEmpty(treeList)) {
            List<Tree<String>> findList = treeList.stream().filter(tree -> tree.getName().equals(orgName)).collect(Collectors.toList());
            if(ObjectUtil.isNotEmpty(findList)) {
                if(iterator.hasNext()) {
                    return findRepairItemIdByName(findList.get(0).getId(), iterator, cachedAllOrgList, findList.get(0).getChildren());
                } else {
                    return findList.get(0).getId();
                }
            }
        }
        String orgId = this.doCreateRepairItem(parentId, orgName, cachedAllOrgList);
        if(iterator.hasNext()) {
            return findRepairItemIdByName(orgId, iterator, cachedAllOrgList, CollectionUtil.newArrayList());
        } else {
            return orgId;
        }
    }

    /**
     * 执行创建机构
     *
     * @author xuyuxiang
     * @date 2023/3/8 9:38
     **/
    public String doCreateRepairItem(String parentId, String orgName, List<RepairItem> cachedAllOrgList) {
        //创建该机构
        RepairItem bizOrg = new RepairItem();
        bizOrg.setName(orgName);
        bizOrg.setCode(RandomUtil.randomString(10));
        bizOrg.setParentId(parentId);
        //bizOrg.setCategory(parentId.equals("0")?RepairItemCategoryEnum.COMPANY.getValue():RepairItemCategoryEnum.DEPT.getValue());
        bizOrg.setSortCode(99);
        this.save(bizOrg);
        // 发布增加事件
        CommonDataChangeEventCenter.doAddWithData(BizDataTypeEnum.REPAIRITEM.getValue(), JSONUtil.createArray().put(bizOrg));
        // 将该机构加入缓存
        cachedAllOrgList.add(bizOrg);
        // 更新缓存
        commonCacheOperator.put(REPAIRITEM_CACHE_ALL_KEY, cachedAllOrgList);
        return bizOrg.getId();
    }

    /* ====机构部分所需要用到的选择器==== */

    @Override
    public List<Tree<String>> repairItemTreeSelector() {
        LambdaQueryWrapper<RepairItem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            lambdaQueryWrapper.in(RepairItem::getId, loginUserDataScope);
        } else {
            return CollectionUtil.newArrayList();
        }
        lambdaQueryWrapper.orderByAsc(RepairItem::getSortCode);
        List<RepairItem> bizOrgList = this.list(lambdaQueryWrapper);
        List<TreeNode<String>> treeNodeList = bizOrgList.stream().map(bizOrg ->
                new TreeNode<>(bizOrg.getId(), bizOrg.getParentId(), bizOrg.getName(), bizOrg.getSortCode()))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    /* ====以下为各种递归方法==== */

    public List<RepairItem> getParentAndChildListById(List<RepairItem> originDataList, String id, boolean includeSelf) {
        List<RepairItem> parentListById = this.getParentListById(originDataList, id, false);
        List<RepairItem> childListById = this.getChildListById(originDataList, id, true);
        parentListById.addAll(childListById);
        return parentListById;
    }

    public List<RepairItem> getChildListById(List<RepairItem> originDataList, String id, boolean includeSelf) {
        List<RepairItem> resultList = CollectionUtil.newArrayList();
        execRecursionFindChild(originDataList, id, resultList);
        if(includeSelf) {
            RepairItem self = this.getById(originDataList, id);
            if(ObjectUtil.isNotEmpty(self)) {
                resultList.add(self);
            }
        }
        return resultList;
    }

    public List<RepairItem> getParentListById(List<RepairItem> originDataList, String id, boolean includeSelf) {
        List<RepairItem> resultList = CollectionUtil.newArrayList();
        execRecursionFindParent(originDataList, id, resultList);
        if(includeSelf) {
            RepairItem self = this.getById(originDataList, id);
            if(ObjectUtil.isNotEmpty(self)) {
                resultList.add(self);
            }
        }
        return resultList;
    }

    public void execRecursionFindChild(List<RepairItem> originDataList, String id, List<RepairItem> resultList) {
        originDataList.forEach(item -> {
            if(item.getParentId().equals(id)) {
                resultList.add(item);
                execRecursionFindChild(originDataList, item.getId(), resultList);
            }
        });
    }

    public void execRecursionFindParent(List<RepairItem> originDataList, String id, List<RepairItem> resultList) {
        originDataList.forEach(item -> {
            if(item.getId().equals(id)) {
                RepairItem parent = this.getById(originDataList, item.getParentId());
                if(ObjectUtil.isNotEmpty(parent)) {
                    resultList.add(parent);
                }
                execRecursionFindParent(originDataList, item.getParentId(), resultList);
            }
        });
    }

    public RepairItem getById(List<RepairItem> originDataList, String id) {
        int index = CollStreamUtil.toList(originDataList, RepairItem::getId).indexOf(id);
        return index == -1?null:originDataList.get(index);
    }

    public RepairItem getParentById(List<RepairItem> originDataList, String id) {
        RepairItem self = this.getById(originDataList, id);
        return ObjectUtil.isNotEmpty(self)?self:this.getById(originDataList, self.getParentId());
    }

    public RepairItem getChildById(List<RepairItem> originDataList, String id) {
        int index = CollStreamUtil.toList(originDataList, RepairItem::getParentId).indexOf(id);
        return index == -1?null:originDataList.get(index);
    }
}
